class Router {

    static getInstance() {
        if(!Router.instance){
            Router.instance = new Router();
        }
        return Router.instance;
    }

    add()
    {
        CONFIG.keydownAddRouterBtn = true;
        CONFIG.drawingRouterEdgePoints=[];
        setRouteName();
        showDrawController();

    }

    /**
     * 1)格式化ScheduleTime为int类型
     * 2）按照SchudeuleTime 开始时间升序，结束时间升序
     * 3）Route信息写入队列任务
     * @param id
     */
    calculateRouterInfo( routerId )
    {
        this.getCustmoerArriverStarTimeAndArriverEndTime( routerId )
        this.optimizeOrderpoints( routerId );
        let routers =OBJECT.routerPonits[routerId].points;

        let color  = OBJECT.routersBgColorMap[routerId];
        return new Promise( (resolve ,reject)=>{
              this.calculateRoute( routers ,routerId, color ,resolve , reject)
        });
    }

    /**
     * 计算Router 请求API显示地图
     * @param routers
     * @param routerId
     * @param color
     * @param resovle
     * @param reject
     */
    calculateRoute( routers ,routerId, color ,resolve , reject) {
        var _this = this;
        Router.getInstance().setData( routerId ,routers );
        let len = routers.length;
        let  end_piont = routers[len-1];
        let directionsService = new google.maps.DirectionsService;
        OBJECT.directionsDisplay[routerId] = new google.maps.DirectionsRenderer({
            "routerId":routerId ,   //地图唯一表示，对应数据库主键
            "routers":routers,
            suppressMarkers : true,
            polylineOptions: {
                strokeColor: color,
                strokeOpacity:0.7
            }
        });
        directionsService.route({
            origin:{lat:Number(CONFIG.wareHouseCenter.lat) , lng:Number(CONFIG.wareHouseCenter.lng)},
            destination: {lat: parseFloat(end_piont.lat) , lng:parseFloat(end_piont.lng) },
            travelMode: 'DRIVING',
            optimizeWaypoints:false,
            waypoints:_this.getWayPionts(routers)
        }, function(response, status) {
            console.log(routerId,status,new Date().toLocaleTimeString())
            if (status === 'OK') {
                OBJECT.directionsDisplay[routerId].setDirections(response);
                Router.getInstance().setRouteSchedule( routerId );
                CONFIG.showRouters &&  Router.getInstance().showOneRouters( routerId );
                resolve('SUCCESS');

            } else if( status=='MAX_WAYPOINTS_EXCEEDED') {
                $.Pro('最大不能超过24个站点');
                colseLoading();
                //delete OBJECT.directionsDisplay[routerId];
                reject(status);

            }
            else if(status == 'UNKNOWN_ERROR')
            {
                reject(status);
                $.Pro('网络异常，请重试~~');
            }
        });

    }

    /**
     * 计算到达客户地点的最早时间和最晚时间
     * @param routerId
     */
    getCustmoerArriverStarTimeAndArriverEndTime(routerId)
    {
        OBJECT.routerPonits[routerId].points.forEach( function ( value , index) {
                 let t =OBJECT.routerPonits[routerId].points[index].ScheduleTime.split('--');
                 let arriveStartTimeString = Number(t[0].replace(':',''));
                 let arriveEndTimeString   = Number(t[1].replace(':',''));
                 OBJECT.routerPonits[routerId].points[index].arriveStartTimeString = arriveStartTimeString
                 OBJECT.routerPonits[routerId].points[index].arriveEndTimeString  = arriveEndTimeString
                 OBJECT.routerPonits[routerId].points[index].priority  = ( arriveEndTimeString + arriveStartTimeString ) / 2     //排序优先值


        })

    }

    /**
     * 路线最优排序
     * @param routerId
     */
    optimizeOrderpoints (routerId)
    {
          // alert(CONFIG.optimizeOrderpoints[routerId]+'test')
           if( CONFIG.optimizeOrderpoints[routerId])
           {
               let points = OBJECT.routerPonits[routerId].points;
               points.sort(function (a, b) {
                   return SortByProps(a, b, { "priority": "ascending" ,"arriveEndTimeString":"ascending"});
               });
               OBJECT.routerPonits[routerId].points = points;
               CONFIG.optimizeOrderpoints[routerId] = false;

           }
    }
    /**
     * 获取途经点
     * @param waypoints
     * @returns {*}
     */
    getWayPionts (waypoints) {

        if(waypoints.length==1){   //不存在途经点
            return [];
        }else{
            var json=[];
            for(var i=0;i < waypoints.length; i++ ){
                var arr={};
                var temp={};
                temp.lat= parseFloat(waypoints[i].lat);
                temp.lng= parseFloat(waypoints[i].lng);
                arr.location = temp;
                json.push(arr);

            }
            return json;
        }
        return wayPointsJson;
    }
    /**
     * 设置数据
     * @param routerId
     * @param data
     */
    setData(routerId , data){
        OBJECT.routerPonits[routerId] = OBJECT.routerPonits[routerId] || {}
        OBJECT.routerPonits[routerId].UpdateStatus = false;

    }
    /**
     * 设置路线每个点之间的时间和路程
     * @param routerId
     */
    setRouteSchedule ( routerId ) {
        let wayPonits = OBJECT.directionsDisplay[routerId].getDirections();
        let schedule =  wayPonits.routes[0].legs;
        let ret = [];
        schedule.forEach(function ( value , index ) {
            let t ={distance:value.distance,duration:value.duration};
            ret.push( t );
        })
        OBJECT.routerPonits[routerId].schedule = ret;

    }
    /**
     * 设置当前操作的路由id
     * @param routerId
     */
    setCurrentRouterId( routerId){
        CONFIG.currentOpearateRouterId = routerId;
    }
    /**
     * 获取当前操作的路由id
     * @param routerId
     */
    getCurrentRouterId(){
        return CONFIG.currentOpearateRouterId || null;
    }

    /**
     * 删除一个区域和他的属性
     * @param routerId
     */
    removeRouter(routerId)
    {
        delete OBJECT.routerPonits[routerId];
        delete OBJECT.dispalyPositonList[routerId];
        delete OBJECT.routerEdgePoints[routerId];
        delete OBJECT.directionsDisplay[routerId];
    }

    /**
     * 设置Router的更新状态
     * @param routerId
     * @param status
     */
    setRouterUpdateStatus( routerId, status)
    {
          return OBJECT.routerPonits[routerId].UpdateStatus = status;
    }

    /**
     * 把路线的ABCDEFG顺序改成123456
     * @param position
     * @param i
     * @returns {google.maps.Marker}
     */
    addMarkerOnRouter(position, i , routerId) {
        let _this = this;
        OBJECT.numberMarkerOnRouter[routerId] =  new google.maps.Marker({
            // @see http://stackoverflow.com/questions/2436484/how-can-i-create-numbered-map-markers-in-google-maps-v3 for numbered icons
            icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + i + '|0095ff|FFF',
            position: position,
            map: map,
            routerId:routerId
        })
        OBJECT.numberMarkerOnRouter[routerId].addListener('click',function () {
            _this.showMoveRouterTemplate(this.routerId)
        });
    }

    /**
     * 隐藏路线的数字market
     * @param position
     * @param i
     * @returns {google.maps.Marker}
     */
    hideMarkerOnRouter( routerId) {
       OBJECT.numberMarkerOnRouter[routerId].setMap( null );
    }
    /**
     * 在路线的显示ABCDEFG改成123456
     * @param position
     * @param i
     * @returns {google.maps.Marker}
     */
    showNumberMarkOnRouter(routerId)
    {
            let routerPointsInfo = OBJECT.directionsDisplay[routerId].getDirections();
            let route = routerPointsInfo.routes[0];

            this.addMarkerOnRouter(route.legs[0].start_location,0, routerId);  //仓库为数字为0
            let markerCounter=0;
            for (let i = 0; i < route.legs.length; i++) {
                this.addMarkerOnRouter(route.legs[i].start_location, markerCounter++ , routerId);

            }
    }

    /**
     * 司机是否已经分配了
     * @param driverId
     * @returns {boolean}
     * @constructor
     */
    DriverIsAssign( driverId)
    {
        for( let routerId in OBJECT.routerPonits)
        {
            if( OBJECT.routerPonits[routerId].driverId == driverId )
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 显示所有的路线
     */
    showAllRouters()
    {
        for(let routerId in OBJECT.directionsDisplay)
        {
            OBJECT.directionsDisplay[routerId].setMap( map );
            this.showNumberMarkOnRouter(routerId);
        }

    }

    /**
     * 显示一条Router信息
     * @param routerId
     */
    showOneRouters(routerId)
    {
        OBJECT.numberMarkerOnRouter[routerId].setMap( map ) // 移除Router上的数字标记
        OBJECT.directionsDisplay[routerId].setMap( map );
        this.showNumberMarkOnRouter(routerId);
    }
    /**
     * 显示所有的路线
     */
    hideAllRouters()
    {
        for(let routerId in OBJECT.directionsDisplay)
        {
            OBJECT.directionsDisplay[routerId].setMap( null );
            this.hideMarkerOnRouter(routerId);
        }
    }

    /**
     * 显示移动Router列表模板 新打开一个弹出层
     * @param routerId
     */
    showMoveRouterTemplate(routerId)
    {

        this.setCurrentRouterId( routerId );
        let customers = this.getCustomerOnRouters( routerId );
        let routers  = this.getRoutersListNotSelf( routerId );
        let source=$('#move-routers-template').html();
        let template = Handlebars.compile(source);
        let html = template({customers:customers,routers:routers,territoryName:OBJECT.routersNameMap[routerId]});
        let routerPoints = this.clone(OBJECT.routerPonits)
      //  let routerPoints = $.extend(OBJECT.routerPonits,{})
        console.log(routerPoints)
        let _this = this;
        layer.open({
            title:"Move Routers",
            type: 1,
            area:['800px','400px'],
            btn: ['确定', '取消'],
            yes:function () {

                 _this.moveRoutersToOtherTerritoy(routerPoints);  //=5

            },
            content: html
        });
        //

    }

    /**
     * 获取Router的客户列表
     * @param routerId
     * @returns {Array}
     */
    getCustomerOnRouters(routerId)
    {
          let points = OBJECT.routerPonits[routerId].points;
          let result=[];
          points.forEach( value =>{
              result.push(value)
          })
          return result;
    }

    /**
     * 获取除了当前的剩下的Roters
     * @param routerId
     * @returns {Array}
     */
    getRoutersListNotSelf( routerId)
    {
        let result = [];
        for (let key in OBJECT.routerPonits)
        {
              if( key!=routerId )
              {
                   result.push({routerId:key,routerName:OBJECT.routersNameMap[key]});
              }
        }
        return result;
    }

    clone(obj)
    {
      let objClone = Array.isArray(obj)?[]:{};
       if(obj && typeof obj==="object"){
           for(let key in obj){
               if(obj.hasOwnProperty(key)){
                   //判断ojb子元素是否为对象，如果是，递归复制
                   if(obj[key]&&typeof obj[key] ==="object"){
                       objClone[key] = this.clone(obj[key]);
                   }else{
                       //如果不是，简单复制
                       objClone[key] = obj[key];
                   }
               }
           }
       }
       return objClone;

    }

    /**
     * 移动Router到另一个Territoy
     * @returns {boolean}
     */
    moveRoutersToOtherTerritoy(routerPoints)
    {



        let customers = $('.move-router .customer-list .selected');
        let router =   $('.move-router .router-list .selected');
        if( customers.size()==0)
        {
            layer.msg('至少要选择一个客户~')
            return false;
        }
        if( router.size()==0)
        {
            layer.msg('Territory 不能为空~')
            return false;
        }

        console.log(routerPoints,'your is best one')
        let destinationRouterId = router.data('router');   //移动的目标Router
        let currentRouterId = this.getCurrentRouterId();
        this.saveBeforeMoveRouters(currentRouterId , destinationRouterId );   //保存移动之前的数据



        let deleteRemoveKeys = new Set();
        let afterRemoveSchedule=[];    //被移动后的Terrtiory的Schedule
        let afterRemovePoints =[];      //被移动后的Terrtiory的Points
        //遍历选中了的客户

        $.each(customers,function (key,value) {
            let customer = $(value).data('customer');
            let removeKey = $(value).data('key');
            OBJECT.routerPonits[destinationRouterId].points.push(customer);   //目标Territoypush一个新的客户
            OBJECT.test.push(customer)

            deleteRemoveKeys.add(removeKey);//当前Territoy remvoe一个客户key值
        });

        //给当前Terrtitory重新赋值
        OBJECT.routerPonits[currentRouterId].points.forEach( function (value ,index) {
                 if(!deleteRemoveKeys.has(index)){
                      afterRemovePoints.push(value);
                      afterRemoveSchedule.push( OBJECT.routerPonits[currentRouterId].schedule[index])
                      OBJECT.test.push(OBJECT.routerPonits[currentRouterId].schedule[index])
                 }
        });

        OBJECT.routerPonits[currentRouterId].points = afterRemovePoints;
        OBJECT.routerPonits[currentRouterId].schedule = afterRemoveSchedule;
        layer.closeAll();
        Queue(destinationRouterId);
        Queue(currentRouterId);

    }

    /**
     * 保存移动router到另一个routers之前的数据
     * @param currentRouterId  当前操作的RouterId
     * @param destinationRouterId  移动目标的RouterId
     */
    saveBeforeMoveRouters( currentRouterId, destinationRouterId )
    {

           OBJECT.beforeMoveToOthersRouters[currentRouterId] = OBJECT.routerPonits[currentRouterId];
           OBJECT.beforeMoveToOthersRouters[destinationRouterId] = OBJECT.routerPonits[destinationRouterId];
    }

    /**
     * 恢复到上一次移动router之前的数据
     */
    renewBeforeMoveRouters()
    {
       //  let currentRouterId = OBJECT.beforeMoveToOthersRouters[0].routerId;
         // let destinationRouterId = OBJECT.beforeMoveToOthersRouters[1].routerId;
        /*  OBJECT.routerPonits[currentRouterId] = OBJECT.beforeMoveToOthersRouters[0];   //把移动之前的数据重新赋值给当前router*/
         // OBJECT.routerPonits[destinationRouterId] = OBJECT.beforeMoveToOthersRouters[1]; //把移动之前的数据重新赋值给目标router
        //移动之前的数据重新赋值给目标router && 移动之前的数据重新赋值给目标router
        /*  OBJECT.beforeMoveToOthersRouters.forEach( function (value ,index) {
              console.log(index,value)
              OBJECT.routerPonits[index] = value;
          });*/
          for (let routerId in OBJECT.beforeMoveToOthersRouters)
          {
             // console.log(OBJECT.routerPonits[routerId])
              OBJECT.routerPonits[routerId] = OBJECT.beforeMoveToOthersRouters[routerId];
             // console.log(OBJECT.routerPonits[routerId])
              //重新生成router
              Queue(routerId);
          }
          //重新生成router
         // Queue(currentRouterId);
         // Queue(destinationRouterId);
    }



}
